package api;



import java.io.BufferedReader;
import java.io.FileReader;


import org.python.core.PyObject;
import org.python.core.PyString;
import org.python.core.PySystemState;
import org.python.util.PythonInterpreter;

import weka.attributeSelection.AttributeSelection;
import weka.attributeSelection.CfsSubsetEval;
import weka.attributeSelection.GreedyStepwise;
import weka.core.Instances;
import weka.filters.Filter;
import weka.filters.unsupervised.attribute.Remove;



public class AttributeFiltering {
	
	
	private Instances inst;
	AttributeSelection filter;
	CfsSubsetEval eval;
	GreedyStepwise search;
	Remove remove;
	String filename;
	String [] indexesForProteins;

	public AttributeFiltering(String filename) {
		inst = this.readData(filename);
		filter = new AttributeSelection();
		eval = new CfsSubsetEval();
		search = new GreedyStepwise();
		remove = new Remove();
		this.filename = filename;
	}

	public FilteredResult getFilteredData() throws Exception {
		
		String rangeList = findAttributeIndices(filename);
		remove.setAttributeIndices(rangeList);
		remove.setInvertSelection(true);
		remove.setInputFormat(inst);
		Instances instNew = Filter.useFilter(inst, remove);
		instNew.setClassIndex(instNew.numAttributes() - 1);
		return new FilteredResult(instNew, indexesForProteins);
	}

	private String findAttributeIndices(String filename) {
		
		PySystemState state = new PySystemState();
		state.argv.append(new PyString(filename));
		state.argv.append(new PyString("17"));
		state.argv.append(new PyString("pssm,chemprop_hyd,helix,psic_numSeq,relW,prosite,perc,profbval_raw,class"));
		
		PythonInterpreter interpreter = new PythonInterpreter(null, state);
		interpreter.execfile("misc/filterAttributes.py");
		PyObject someFunc = interpreter.get("ftCol");
		PyObject someFunc2 = interpreter.get("proRange");
		indexesForProteins = (String[]) someFunc2.__tojava__( String[].class);	
		return someFunc.__tojava__(String.class).toString();	
	}
	
	private Instances readData(String fileName) {
		inst = null;
		try {
			BufferedReader reader = new BufferedReader(new FileReader(fileName));
			inst = new Instances(reader);
			reader.close();
			// setting class attribute
			inst.setClassIndex(inst.numAttributes() - 1);
		} catch (Exception ex) {
			ex.printStackTrace();
		}		
		
		return inst;
	}
	
}


